# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from ..model.modelInfo import *
from rest_framework import generics
from rest_framework import status


class GlbFileListCreateView(generics.ListCreateAPIView):
    """
    GLB文件列表查询和创建接口
    """

    queryset = GlbFile.objects.all()
    serializer_class = GlbFileSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        # 创建GLB文件后，自动创建对应的配置记录
        glb_file = serializer.instance
        ModelConfig.objects.create(glb_file=glb_file)

        headers = self.get_success_headers(serializer.data)
        return Response(
            serializer.data, status=status.HTTP_201_CREATED, headers=headers
        )


class GlbFileRetrieveUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    """
    GLB文件查询单个、更新和删除接口
    """

    queryset = GlbFile.objects.all()
    serializer_class = GlbFileSerializer

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()

        # 先删除关联的ModelConfig记录，避免外键约束错误
        try:
            model_config = instance.config
            if model_config:
                model_config.delete()
        except ModelConfig.DoesNotExist:
            pass

        # 然后删除GlbFile记录
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)
